﻿namespace KeRui.Upload
{
    using System;
    using System.Collections;

    internal class SharedState
    {
        private static Hashtable sStateInfoDB = new Hashtable();

        public static StateInfo Create(int inID)
        {
            Purge();
            StateInfo info = new StateInfo(inID, "", Settings.Current.Advanced.ChunkSize);
            lock (sStateInfoDB.SyncRoot)
            {
                sStateInfoDB[inID] = info;
            }
            return info;
        }

        public static void Delete(int inID)
        {
            lock (sStateInfoDB.SyncRoot)
            {
                sStateInfoDB.Remove(inID);
            }
            Purge();
        }

        public static StateInfo Find(int inID)
        {
            StateInfo info = (StateInfo) sStateInfoDB[inID];
            if (info == null)
            {
                info = new StateInfo(inID, Settings.Current.Notes.Connecting, Settings.Current.Advanced.ChunkSize);
            }
            return info;
        }

        public static int[] GetIDs()
        {
            int[] numArray;
            lock (sStateInfoDB.SyncRoot)
            {
                numArray = new int[sStateInfoDB.Count];
                sStateInfoDB.Keys.CopyTo(numArray, 0);
            }
            return numArray;
        }

        public static int GetNewID()
        {
            return new Random().Next();
        }

        private static void Purge()
        {
            lock (sStateInfoDB.SyncRoot)
            {
                ArrayList list = new ArrayList();
                foreach (DictionaryEntry entry in sStateInfoDB)
                {
                    StateInfo info = (StateInfo) entry.Value;
                    if (info.Expired())
                    {
                        list.Add(entry.Key);
                    }
                }
                foreach (object obj2 in list)
                {
                    sStateInfoDB.Remove(obj2);
                }
            }
        }
    }
}

